
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class UserServiceCglib implements MethodInterceptor, Callback {
  private static final Logger LOG = LoggerFactory.getLogger(UserServiceCglib.class);

  public Object target;

  public UserServiceCglib(Object targetObj){
    target = targetObj;
  }

  public Object getProxyInstance(){
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(target.getClass());
    enhancer.setCallback(this);
    return enhancer.create();
  }

  @Override
  public Object intercept(Object obj, Method method, Object[] params, MethodProxy methodProxy) throws Throwable {
    LOG.info("事务开始执行");
    Object result = methodProxy.invokeSuper(obj, params);
    LOG.info("事务结束");
    return result;
  }
}
